package com.github.data_manage.dao

import com.github.data_manage.domain.po.FundNavData
import org.springframework.data.jpa.repository.Modifying
import org.springframework.data.jpa.repository.Query
import org.springframework.data.repository.query.Param
import org.springframework.transaction.annotation.Transactional
import java.math.BigDecimal
import java.time.LocalDate
import java.time.LocalDateTime

/**
 *@author CHN
 *@since 2024-08-10 14:48
 */
interface FundNavDataDao : BaseDao<FundNavData> {

    @Query("select f from FundNavData f where f.fundId = :fundId order by f.time desc ")
    fun findAllByFundId(@Param("fundId") fundId: Int): List<FundNavData>

    @Query("select f from FundNavData f where f.fundId = :fundId and f.time between :startTime and :endTime order by f.time desc ")
    fun findAllByFundIdAndTimeBetween(
        @Param("fundId") fundId: Int,
        @Param("startTime") startTime: LocalDate,
        @Param("endTime") endTime: LocalDate
    ): List<FundNavData>

    @Query("select f from FundNavData f where f.fundId = :fundId and f.time <= :lastMonth order by f.time desc limit 1")
    fun findLastNavDataByFundId(
        @Param("fundId") fundId: Int,
        @Param("lastMonth") lastMonthEndTime: LocalDate
    ): FundNavData?

    fun findFundNavDataByFundIdAndTime(fundId: Int, time: LocalDate): FundNavData?

    @Query("select max(f.value) from FundNavData f where f.fundId = :fundId and f.time <= :time order by f.time desc limit 1")
    fun findMaxValueByFundIdAndTime(@Param("fundId") fundId: Int, @Param("time") time: LocalDate): BigDecimal?

    @Query("select f from FundNavData f where f.fundId = :fundId and f.time <= :time order by f.time desc limit 1")
    fun findByFundIdAndTimeAndContrastName(
        @Param("fundId") fundId: Int,
        @Param("time") lastMonthEndTime: LocalDate
    ): List<FundNavData>

    @Modifying
    @Transactional
    fun deleteAllByFundId(fundId: Int)

    @Query("select f from FundNavData f where f.fundId = :fundId and f.time <= :atEndOfMonth order by f.time ")
    fun findAllByFundIdAndTime(fundId: Int, atEndOfMonth: LocalDate): List<FundNavData>


    fun findAllByFundIdIn(fundIds: List<Int>): List<FundNavData>

    @Modifying
    @Query("update FundNavData f set f.fundName = :fundName where f.fundId = :fundId")
    fun updateFundNameByFundId(
        @Param("fundId") fundId: Int,
        @Param("fundName") name: String
    )

}
